/*
 * @Author: rogi
 * @Date: 2022-11-02 10:06:00
 * @LastEditTime: 2022-12-06 17:38:40
 * @LastEditors: rogi
 * @Description: 描述
 */
import { postMessageType, getUserInfoType, newsType } from './type/index'
// import history from '@/router/history'
const { origin, pathname }: any = window.location;
let iframeId: String = origin + pathname
const messageTypeMap: any = {
  getHistory: (data: any) => {
    const historyList = JSON.parse(localStorage.getItem('historyList') || "[]") || []
    const historyId = localStorage.getItem('historyId')
    const index = historyList.findIndex((el: any) => el.id === historyId)
    message({
      type: "getHistory",
      data: {
        back: historyList[index - 1],
        forward:  historyList[index + 1], 
        subApp: true,
        code: 200
      },
      iframeId: data.iframeId,
      taskId: data.taskId
    })
  },
  historyBack: (data: any) => {
    const historyList = JSON.parse(localStorage.getItem('historyList') || "[]") || []
    const historyId = localStorage.getItem('historyId')
    const index = historyList.findIndex((el: any) => el.id === historyId)
    const back = historyList[index - 1]
    localStorage.setItem('historyId', back.id)
    window.location.href = String(back.href)
  },
  historyForward: (data: any) => {
    const historyList = JSON.parse(localStorage.getItem('historyList') || "[]") || []
    const historyId = localStorage.getItem('historyId')
    const index = historyList.findIndex((el: any) => el.id === historyId)
    const back = historyList[index + 1]
    localStorage.setItem('historyId', back.id)
    window.location.href = String(back.href)
  },
  historyRefresh: (data: any) => {
    window.history.go(0)
  },
  historyInit: (res: any) => {
    const uuid = generateUUID()
    // console.log('datadatadatadata', res)
    localStorage.setItem('historyList', JSON.stringify([{  href: res.data.initUrl, id: uuid }]))
    localStorage.setItem('historyId', uuid)
  }
}



/**
 * @description: 发送父级
 * @param {postMessage} option
 * @return {*}
 */
const postMessage = (option: postMessageType) => {
  return new Promise(async (resolve, rejects) => {
    const taskId = generateUUID()
    // window.parent.postMessage({
    //   type: option.type,
    //   iframeId,
    //   taskId,
    //   option: option.data
    // }, "*");
    message({
      ...option,
      taskId,
      iframeId
    })
    const res = await checkTaskQueue(taskId)
    resolve(res)
  })
}

const message = (option: any) => {
  window.parent.postMessage({
    type: option.type,
    iframeId: option.iframeId,
    taskId: option.taskId,
    option: option.data,
    data: option.data
  }, "*");
}

let taskQueue:any = {} // 任务队列

/**
 * @description: 检查任务队列
 * @param {any} uuid // 任务id
 * @return {*} 从父级窗口返回的内容
 */
let checkTaskQueue = (uuid: any) => {
  return new Promise((resolve, rejects) => {
    taskQueue[uuid] = null
    taskQueue = new Proxy(taskQueue || [], {
      set: (target: any, prop: any, value: any) => {
        target[prop] = value;
        if (value && value.taskId === uuid) {
          if (value.data && value.data.code !== 200) {
            rejects(value)
          }
          resolve(value)
        }
        delete taskQueue[value ? value.taskId : '']
        return true
      }
    })
  })
}

/**
 * @description: 获取用户
 * @param {getUserInfoType} option
 * @return {*}
 */
const getUserInfo = async () => {
  return postMessage({type: "getUserInfo"})
}

/**
 * @description: 消息通知
 * @param {newsType} option
 * @return {*}
 */
const news = async (option: newsType) => {
  return postMessage({type: "news", data: {
    title: option.title,
    type: option.type || 'info',
    component: option.component || 'message',
    description: option.description
  }})
}

/**
 * @description: 关闭当前应用
 * @return {*}
 */
const closeApplication = async () => {
  return postMessage({type: "closeApplication"})
}

/**
 * @description: 通知主程序最大化窗口
 * @return {*}
 */
const maximizeWindow = async () => {
  return postMessage({type: "maximizeWindow"})
}

/**exitAccountexitAccount
 * @description: 最小化窗口
 * @return {*}
 */
const minimizeWindows = async () => {
  return postMessage({type: "minimizeWindows"})
}

const exitAccount = async () => {
  return postMessage({type: "exitAccount"})
}

/**
 * @description: 获取唯一的uuid
 * @return {*}
 */
function generateUUID() {
  var d = new Date().getTime();
  if (window.performance && typeof window.performance.now === "function") {
      d += performance.now(); //use high-precision timer if available
  }
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      var r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}
function init () {
  window.onmessage = function(event: any){
    const { data } = event
    if (!data.subApp) {
      if (data.taskId) {
        taskQueue[data.taskId] = data
      }
      messageTypeMap[data.type] && messageTypeMap[data.type](event.data)
    } else {
      messageTypeMap[data.type] && messageTypeMap[data.type](event.data)
    }
  }
}

export default {
  getUserInfo,
  news,
  closeApplication,
  maximizeWindow,
  minimizeWindows,
  exitAccount, 
  init
}